<script setup>
import ProTable from '@/components/ProTable/index.vue'
import Details from '@/components/ProTable/Details.vue'
import { computed, onMounted, reactive, ref, watchEffect } from 'vue'
import WarningTextBtn from '@/components/ProTable/WarningTextBtn.vue'
import Radar from '@brother/Radar'
import { parseTime, downloadFile } from '@/utils/index'
import {
  queryInspectProject,
  querySubListByProjId,
  queryRoleRelevanceUsers,
  downloadPost,
  inspectPlanTurnover,
  inspectPlanResultScoreExport,
  getDownloadName,
  del,
  getTable,
  add,
  edit,
  getDetail,
  querySameMonthInspectInfo,
  checkSameMonthInspectEdit,
  getSendEmailList,
  sendInspectPlanEmail,
  queryResultScoreForPlan,
  queryResultScoreForPlanV2,
  sendCheckNotificationEmail,
  sendScoreResultEmail,
  exportInspectPlanStatisticsData
} from '@/api/modelQuality/inspectPlan'
import { Message } from 'element-ui'
import { useGetEnum } from '@/components/ProTable/public.js'
import { useGetConfig } from './config'
import LogDialog from '@/components/logManage/dialog'
import { REVIEW_PLANNING } from '@/utils/log'
import ProjectInfo from '@haisum-cloud/ui-components/packages/ModelPlan/components/Pinfo'
import StatisticsDialog from '@haisum-cloud/ui-components/packages/ModelPlan/components/StatisticsDialog'
import RateResultDialog from '@haisum-cloud/ui-components/packages/ModelPlan/components/RateResultDialog'
import { queryStandardComponentRadarInfo } from '@haisum-cloud/ui-components/packages/api/index'
import { getCurrentSubChartData } from '@brother/Radar/util'

const { getEnumlabel, optionFunc } = useGetEnum()

const {
  tableColumn,
  searchColumn,
  defaultForm,
  formRules,
  permission,
  mainUndertaking,
  observer,
  totalScoreMap
} = useGetConfig()

// 下拉框的数据
const options = reactive({
  project: [], // 工程号/主合同号/项目编号
  subitem: [], // 子项号
  presidingUnit: [] //  主持单位
})
const proTableRef = ref()

// 编辑 的时候 状态不是 0 或者后端返回 false；新增的时候 根据后端返回
const disabled_1 = () => {
  if (isEditFrom.value) { return inspectStatus.value !== '0' || disabledInspect.value }
  return disabledInspect.value
}

// 编辑 并且 状态不是0 的时候 禁用
const disabled_2 = () => inspectStatus.value !== '0' && isEditFrom.value

// 新增&编辑配置项
const formColumn = ref([
  {
    type: 'divider',
    label: '基本信息'
  },
  {
    type: 'slot',
    label: '年份',
    slotName: 'reviewYear',
    dataIndex: 'reviewYear',
    disabled: computed(() => isEditFrom.value)
  },
  {
    type: 'select',
    dataIndex: 'reviewMonth',
    viewName: 'reviewMonthName',
    label: '评审场次',
    option: 'inspect_plan_review_month',
    disabled: computed(() => isEditFrom.value)
  },
  {
    type: 'select',
    dataIndex: 'projId',
    viewName: 'joinStr',
    label: '工程号/主合同号/项目编号',
    placeholder: '请输入关键词',
    option: computed(() => options.project),
    optionLabel: 'joinStr',
    optionValue: 'projId',
    filterable: true,
    change: (e) => projIdChange(e),
    disabled: computed(disabled_2)
  },
  {
    type: 'text',
    dataIndex: 'deptName',
    label: '主承接',
    value: computed(() => currentSelectProjct?.value?.deptName || '--')
  },
  {
    type: 'text',
    dataIndex: 'projName',
    label: '项目名称',
    value: computed(() => currentSelectProjct?.value?.projName || '--'),
    disabled: computed(disabled_2)
  },
  {
    type: 'select',
    dataIndex: 'subId',
    viewName: 'subNo',
    label: '子项号',
    option: computed(() => options.subitem),
    optionLabel: 'subNo',
    optionValue: 'subId',
    filterable: true,
    change: (e) => subIdChange(e),
    disabled: computed(disabled_2)
  },
  {
    type: 'text',
    dataIndex: 'subName',
    label: '子项名称',
    value: computed(() => stateText.subName || '--')
  },
  {
    type: 'select',
    dataIndex: 'declareNode',
    viewName: 'declareNodeName',
    label: '申报节点',
    option: 'inspect_plan_declare_node',
    disabled: computed(disabled_2)
  },
  {
    type: 'multiple',
    dataIndex: 'designSoftware_',
    viewName: 'designSoftwareName',
    label: '设计软件',
    option: 'software',
    disabled: computed(disabled_2),
    parameProcess: [
      'designSoftware',
      (arr) => (arr && arr.join(',')),
      (str) => str.split(',')
    ]
  },
  {
    type: 'textarea',
    dataIndex: 'remark',
    label: '补充信息',
    maxlength: 255
  },
  {
    type: 'divider',
    label: '进度计划'
  },
  {
    type: 'slot',
    label: '完成策划时间',
    slotName: 'finishPlanTime',
    dataIndex: 'finishPlanTime',
    disabled: computed(disabled_1)
  },
  {
    type: 'slot',
    label: '开始审查时间',
    slotName: 'startInspectTime',
    dataIndex: 'startInspectTime',
    disabled: computed(disabled_1)
  },
  {
    type: 'divider',
    label: '参与方信息'
  },
  {
    type: 'text',
    dataIndex: 'deptName',
    label: '被检查方公司',
    value: computed(() => currentSelectProjct?.value?.deptName || '--')
  },
  {
    type: 'text',
    dataIndex: 'inspectionParty',
    viewName: 'providerCompanyAccount',
    label: '被检查方账户',
    value: computed(() => stateText?.inspectionParty || '--')
  },
  {
    type: 'select',
    dataIndex: 'inspect1CompanyId',
    viewName: 'inspect1CompanyName',
    label: '检查方1公司',
    option: mainUndertaking,
    optionValue: 'id',
    optionSlot: 'inspect1CompanyId_optionSlot',
    change: (e) => inspectChange(e, 1),
    disabled: computed(disabled_1)
  },
  {
    type: 'text',
    dataIndex: 'inspectionParty_1',
    viewName: 'inspect1CompanyAccount',
    label: '检查方1账户',
    value: computed(() => stateText?.inspectionParty_1 || '--')
  },
  {
    type: 'select',
    dataIndex: 'inspect2CompanyId',
    viewName: 'inspect2CompanyName',
    label: '检查方2公司',
    optionValue: 'id',
    option: mainUndertaking,
    optionSlot: 'inspect2CompanyId_optionSlot',
    change: (e) => inspectChange(e, 2),
    disabled: computed(disabled_1)
  },
  {
    type: 'text',
    dataIndex: 'inspectionParty_2',
    viewName: 'inspect2CompanyAccount',
    label: '检查方2账户',
    value: computed(() => stateText?.inspectionParty_2 || '--')
  },
  {
    type: 'select',
    dataIndex: 'observerId',
    viewName: 'observerName',
    label: '观察员',
    option: observer,
    optionLabel: 'label',
    optionValue: 'userId',
    disabled: computed(disabled_1)
  },
  {
    type: 'divider',
    label: '会议信息'
  },
  {
    type: 'date',
    dataIndex: 'meetingDate',
    label: '会议日期',
    disabled: computed(disabled_1)
  },
  {
    type: 'select',
    dataIndex: 'meetingTime',
    label: '会议时间',
    option: 'inspect_plan_meeting_time',
    optionValue: 'label',
    disabled: computed(disabled_1)
  },
  {
    type: 'select',
    dataIndex: 'presideCompanyId',
    viewName: 'presideCompanyName',
    label: '主持单位',
    optionValue: 'id',
    option: computed(() => options.presidingUnit),
    disabled: computed(disabled_1)
  },
  {
    type: 'input',
    dataIndex: 'meetingNo',
    label: '会议号',
    maxlength: 20,
    disabled: computed(disabled_1)
  },
  {
    type: 'input',
    dataIndex: 'meetingPassword',
    label: '会议密码',
    maxlength: 20,
    disabled: computed(disabled_1)
  },
  {
    type: 'textarea',
    dataIndex: 'meetingRemark',
    label: '其他信息',
    maxlength: 255
  }
])

const disabledInspect = ref(false)

// 表单中 目前选中的项目
const currentSelectProjct = ref({})
// 表单中 静态显示的信息
const stateText = reactive({
  subName: '', // 子项名称
  inspectionParty: '', // 被检查方公司
  inspectionParty_1: '', // 检查方1账户
  inspectionParty_2: '' // 检查方2账户
})

const projIdChange = (projId, isEdit) => {
  currentSelectProjct.value = options.project.find(
    (item) => item.projId === projId
  )

  // 查询评分员信息并更新状态文本
  queryRoleRelevanceUsers({
    roleName: '评分员',
    deptName: currentSelectProjct.value.deptName
  }).then((res) => {
    if (res.length > 0) {
      stateText.inspectionParty = res?.map((item) => item.username)?.join('、')
    } else {
      stateText.inspectionParty = ''
    }
  })

  // 查询项目子项列表并更新选项列表
  return querySubListByProjId({ projId }).then((res) => {
    options.subitem = res
    if (isEdit) return // 避免详情进入清除数据
    detailsRef.value.submitForm['subId'] = null
    stateText.subName = ''
  })
}

const subIdChange = (subId) => {
  // 更新当前子项名称文本
  stateText.subName = options.subitem.find(
    (item) => item.subId === subId
  )?.subName
}

const inspectChange = (id, index, isEdit) => {
  // 更新第一个审查公司的相关信息
  options.presidingUnit[index - 1] = mainUndertaking.value.find(
    (item) => item.id === id
  )
  queryRoleRelevanceUsers({
    roleName: '评分员',
    deptName: options.presidingUnit[index - 1]?.name
  }).then((res) => {
    if (res.length > 0) {
      stateText['inspectionParty_' + index] = res
        ?.map((item) => item.username)
        ?.join('、')
    } else {
      stateText['inspectionParty_' + index] = ''
    }
  })
  if (isEdit) return // 避免详情进入清除数据
  detailsRef.value.submitForm['presideCompanyId'] = null
}

// 弹窗关闭，非常规数据置空
const detailsClose = (isRefresh) => {
  popStatus.value = null
  isEditFrom.value = false
  disabledInspect.value = false
  inspectStatus.value = null
  options.subitem = []
  Object.keys(stateText).forEach((key) => {
    stateText[key] = ''
  })
  currentSelectProjct.value = {}
  if (isRefresh === true) {
    proTableRef.value.onSearch()
  }
}

const detailsRef = ref(null)

const popStatus = ref(null) // 当前弹窗状态 null：关闭 add:新增  edit:编辑 view：查看
const leftOptionChange = (e) => {
  switch (e) {
    case 'export':
      onDownload()
      break
    case 'add':
      detailsRef.value.beforeOpen(e)
      popStatus.value = e
      break

    default:
      console.log('点击事件未定义')
      break
  }
}

const isEditFrom = ref(false)
const inspectStatus = ref(null)
const onEdit = async(row) => {
  isEditFrom.value = true
  inspectStatus.value = row.inspectStatus
  detailsRef.value.beforeOpen('edit', row)
  popStatus.value = 'edit'

  await projIdChange(row.projId, true)
  subIdChange(row.subId)
  inspectChange(row.inspect1CompanyId, 1, true)
  inspectChange(row.inspect2CompanyId, 2, true)
}

const onDetail = (row) => {
  getDetail({ planId: row.planId }).then((res) => {
    detailsRef.value.beforeOpen('view', res)
    popStatus.value = 'view'
  })
}

// 流转标题
const statetUrnoverTitle = (v) => {
  const map = new Map([
    ['0', '“进行中”'],
    ['3', '“已结束”'],
    ['1', '“会议结束”']
  ])
  return `是否将审查状态流转至${map.get(v)}`
}
// 流转操作
const statetUrnover = (row) => {
  const { planId, inspectStatus } = row
  row.loading = true
  /* console.log('findRow', findRow, proTableRef.value.tableData[findIndex].loading=true)*/
  inspectPlanTurnover(planId, inspectStatus).then(() => {
    proTableRef.value.onSearch()
  }).finally(() => {
    row.loading = false
  })
}
// 删除
const onDelete = ({ planId }) => {
  del([planId]).then(() => {
    proTableRef.value.onSearch()
  })
}
// 评分结果
const onScoreResult = ({ planId }) => {
  inspectPlanResultScoreExport({ planId }).then((res) => {
    const blob = new Blob([res], { type: 'application/pdf' })
    const url = window.URL.createObjectURL(blob)
    window.open(url)
  })
}
// 表格多选
const selectionIds = ref([])
const selectionInspectStatus = ref([])
const selectionChange = (e) => {
  selectionIds.value = e.map((item) => item.planId)
  selectionInspectStatus.value = e.map((item) => item.inspectStatus)
}
// 导出
const downloadLoading = ref(false)
const onDownload = () => {
  if (!selectionIds.value.length) { return Message.warning('请先选择要导出的数据!') }
  downloadLoading.value = true
  getDownloadName(selectionIds.value).then((res) => {
    downloadPost(selectionIds.value, res).finally(() => {
      downloadLoading.value = false
    })
  })
}
const downloadLoadingRate = ref(false)
const onDownloadRate = (planId) => {
  let accessRows = []
  if (!planId) {
    accessRows = proTableRef.value.tableData.filter(item => selectionIds.value.includes(item.planId) && !['0'].includes(item.inspectStatus))
    if (accessRows.length === 0) {
      return Message.warning('请先选择要导出的数据!')
    }
  } else {
    accessRows = proTableRef.value.tableData.filter(item => item.planId === planId)
  }

  downloadLoadingRate.value = true
  const ids = accessRows.map(item => item.planId)
  const isSingle = ids.length === 1
  exportInspectPlanStatisticsData({ planIds: ids.join(',') }).then((res) => {
    const format = '{y}{m}{d}{h}{i}{s}'
    if (isSingle) {
      const { reviewYear, reviewMonth, deptName, projCode, subNo } = accessRows[0]
      downloadFile(res, `【评分结果-数据分析】${reviewYear}-${getEnumlabel('inspect_plan_review_month', reviewMonth)}-${deptName}-${projCode}-${subNo}-${parseTime(new Date(), format)}`, 'xlsx', false)
    } else {
      downloadFile(res, `【评分结果-数据分析】${parseTime(new Date(), format)}`, 'zip', false)
    }
  }).finally(() => {
    downloadLoadingRate.value = false
  })
}
// 获取 工程号/主合同号/项目编号 下拉框枚举
const remoteMethod = (query) => {
  return queryInspectProject({ searchStr: query }).then((res) => {
    options.project = res
  })
}

// 监听年份，评审场次，主承接号变动
watchEffect(() => {
  if (!detailsRef.value) return
  const form = detailsRef.value.submitForm
  const deptId = currentSelectProjct.value.deptId
  if (form.reviewYear && form.reviewMonth && deptId) {
    const params = {
      reviewYear: form.reviewYear,
      reviewMonth: form.reviewMonth,
      deptId: deptId
    }
    if (popStatus.value === 'add') {
      effectEditing(params)
    }
    if (popStatus.value === 'edit') {
      // 校验主承接相同月份的审查策划允许编辑
      effectEditing(params).then(() => {
        checkSameMonthInspectEdit(params).then((res) => {
          disabledInspect.value = !res
        })
      })
    }
  }
})

// 校验主承接相同月份的审查策划允许编辑
const effectEditing = (params) => {
  return querySameMonthInspectInfo(params).then((res) => {
    if (Object.keys(res).length) {
      disabledInspect.value = true;
      [
        'inspect1CompanyId',
        'inspect2CompanyId',
        'finishPlanTime',
        'startInspectTime',
        'observerId',
        'meetingDate',
        'meetingTime',
        'meetingNo',
        'meetingPassword'
      ].forEach((item) => (detailsRef.value.submitForm[item] = res[item]))
      inspectChange(res.inspect1CompanyId, 1)
      inspectChange(res.inspect2CompanyId, 2)
      setTimeout(() => {
        detailsRef.value.submitForm.presideCompanyId = res.presideCompanyId
      })
    } else {
      disabledInspect.value = false;
      [
        'inspect1CompanyId',
        'inspect2CompanyId',
        'finishPlanTime',
        'startInspectTime',
        'observerId',
        'meetingDate',
        'meetingTime',
        'meetingNo',
        'meetingPassword',
        'presideCompanyId'
      ].forEach((item) => (detailsRef.value.submitForm[item] = null));

      ['inspectionParty_1', 'inspectionParty_2'].forEach(
        (item) => (stateText[item] = '')
      )
    }
  })
}

const recordsVisible = ref()
const recordsVisibleHandleClose = () => {
  recordsVisible.value = false
}
const recordsTableData = ref()
const onRecords = ({ planId }) => {
  recordsVisible.value = true
  getSendEmailList({ planId }).then((res) => {
    recordsTableData.value = res
  })
}
const sendRecordsLoading_1 = ref(false)
const sendRecordsLoading_2 = ref(false)
const sendRecordsLoading_3 = ref(false)
const onSendRecords = (inx) => {
  if (inx === 1) {
    sendRecordsLoading_1.value = true
    sendInspectPlanEmail(selectionIds.value)
      .then((res) => {
        if (res.status !== '2') return Message.success('发送成功')
        errList.value = res.failList
        errVisible.value = true
      })
      .finally(() => {
        sendRecordsLoading_1.value = false
      })
  }
  if (inx === 2) {
    sendRecordsLoading_2.value = true
    sendCheckNotificationEmail(selectionIds.value)
      .then((res) => {
        if (res.status !== '2') return Message.success('发送成功')
        errList.value = res.failList
        errVisible.value = true
      })
      .finally(() => {
        sendRecordsLoading_2.value = false
      })
  }
  if (inx === 3) {
    sendRecordsLoading_3.value = true
    sendScoreResultEmail(selectionIds.value)
      .then((res) => {
        if (res.status !== '2') return Message.success('发送成功')
        errList.value = res.failList
        errVisible.value = true
      })
      .finally(() => {
        sendRecordsLoading_3.value = false
      })
  }
}
const exportDisabled = computed(() => !selectionIds.value.length)
const exportRateDisabled = computed(() => (!selectionInspectStatus.value.length) || (!selectionInspectStatus.value.find(item => item !== '0')))
// 状态为 未开始 返回 true
const sendRecordsDisabled = computed(() => {
  return (
    selectionInspectStatus.value.includes('1') ||
    selectionInspectStatus.value.includes('2') ||
    selectionInspectStatus.value.includes('3') ||
    !selectionInspectStatus.value.length
  )
})
// 状态为 已结束 返回 true
const sendRecordsDisabled_2 = computed(() => {
  return (
    selectionInspectStatus.value.includes('0') ||
    selectionInspectStatus.value.includes('1') ||
    selectionInspectStatus.value.includes('3') ||
    !selectionInspectStatus.value.length
  )
})

// 查询总分
const totalScore = ref({})
const totalScoreMessage = ref({
  inspectPlanDto: {},
  inspectPlanResultScoreMap: {},
  scoreDetailList: [],
  sumScoreDetailList: []
})
const currentRow = ref(null)
const dialogVisible = ref(false)
const statisticsDialogVisible = ref(false)

const isGetting = ref(false)
const isGettingStatistics = ref(false)
const statisticsData = ref(null)
const viewTotalScore = (rowData) => {
  currentRow.value = rowData
  dialogVisible.value = true
  const { planId } = rowData
  isGetting.value = true
  totalScoreMessage.value = {
    inspectPlanDto: {},
    inspectPlanResultScoreMap: {},
    scoreDetailList: [],
    sumScoreDetailList: []
  }
  queryResultScoreForPlanV2({ planId }).then(res => {
    totalScoreMessage.value = res
  }).finally(() => {
    isGetting.value = false
  })
}

const viewStatistics = (rowData) => {
  statisticsDialogVisible.value = true
  isGettingStatistics.value = true
  statisticsData.value = { chartData: null }
  const { subId, projId, planId } = rowData
  queryStandardComponentRadarInfo({ subId, projId, planId }).then(res => {
    console.log(res)
    if (res) {
      const chartData = getCurrentSubChartData(res, subId)
      statisticsData.value = {
        chartData, ...res
      }
    }
  }).finally(() => {
    isGettingStatistics.value = false
  })
}
const expandAll = ref(false)
const tabs = ref([
  { title: '基本信息', name: 'basicInfo', checked: true },
  { title: '评分表总分', name: 'totalScore', checked: false },
  { title: '各专业分', name: 'majorScore', checked: false, description: '基于评分表结果进行各专业分值统计' },
  { title: '正得分', name: 'positiveScore', checked: false, description: '固化必做项与选做项的分值，已完成的对象进行正加分统计' }
])
const activeNames = ref(tabs.value.filter(item => item.checked).map(item => item.name))
const toggleExpand = () => {
  expandAll.value = !expandAll.value
  tabs.value.forEach(item => {
    item.checked = expandAll.value
  })
  activeNames.value = expandAll.value ? tabs.value.map(item => item.name) : []
}
const handleSingleBtnClick = (row) => {
  row.checked = !row.checked
  activeNames.value = tabs.value.filter(item => item.checked).map(item => item.name)
  expandAll.value = activeNames.value.length === tabs.value.length
}
function handleActiveNameChange(value) {
  tabs.value.forEach(item => {
    item.checked = value.includes(item.name)
  })
  expandAll.value = value.length === tabs.value.length
}
const formatTitle = (row) => {
  return `${row.title}${row.description ? '-(' + row.description + ')' : ''}`
}
const handleClose = () => {
  dialogVisible.value = false
}

const errList = ref([])
const errVisible = ref(false)
const errVisibleHandleClose = () => {
  errVisible.value = false
}

const showLog = ref(false)
const onMailLog = () => {
  showLog.value = true
}

onMounted(() => {
  remoteMethod()
})
</script>

<template>
  <div>
    <ProTable
      ref="proTableRef"
      :get-table="getTable"
      :search-column="searchColumn"
      :table-column="tableColumn"
      :download-loading="downloadLoading"
      :show-left-option="['add', 'export']"
      :disabled-left-option="{ export: exportDisabled,exportText:'导出会议信息' }"
      :permission="permission"
      @selectionChange="selectionChange"
      @leftOptionChange="leftOptionChange"
    >
      <template #left_option>
        <el-button
          type="primary"
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="sendRecordsDisabled || sendRecordsLoading_2"
          :loading="sendRecordsLoading_1"
          @click="onSendRecords(1)"
        >
          发送审查计划
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="sendRecordsDisabled || sendRecordsLoading_1"
          :loading="sendRecordsLoading_2"
          @click="onSendRecords(2)"
        >
          发送检查通知
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="sendRecordsDisabled_2"
          :loading="sendRecordsLoading_3"
          @click="onSendRecords(3)"
        >
          发送评分结果
        </el-button>
        <el-button type="primary" icon="el-icon-message" size="mini" @click="onMailLog()">
          邮件发送日志
        </el-button>
        <el-button type="primary" :loading="downloadLoadingRate" size="mini" icon="el-icon-upload2" :disabled="exportRateDisabled" @click="onDownloadRate()">
          导出评分数据
        </el-button>
      </template>
      <template #table_column_status="{ row }">
        <div class="flex-box-review">
          <div>
            {{ getEnumlabel("inspect_plan_status", row.inspectStatus) }}
          </div>
          <WarningTextBtn
            v-if="['0', '1', '3'].includes(row.inspectStatus)"
            v-permission="permission.turnover"
            color="#e6a23c"
            :cbt="['是', '否']"
            :title="statetUrnoverTitle(row.inspectStatus)"
            :loading="row.loading"
            @confirm="statetUrnover(row)"
          >流转</WarningTextBtn>
        </div>
      </template>
      <template #table_operate="{ row }">
        <div class="operate-box-review">
          <el-button type="text" @click="onDetail(row)"><svg-icon icon-class="detail" /> 详情</el-button>
          <el-button
            v-permission="permission.edit"
            :disabled="['2'].includes(row.inspectStatus)"
            type="text"
            @click="onEdit(row)"
          ><svg-icon icon-class="icon-edit" /> 编辑</el-button>
          <el-popover placement="bottom" trigger="hover" style="margin: 6px 0px 0px 5px;">
            <el-button slot="reference" size="mini" type="text">
              <svg-icon icon-class="more" class="uifix-svg" /> 更多
            </el-button>
            <div
              style="
                display: flex;
                flex-direction: column;
                align-items: flex-start;
              "
            >
              <WarningTextBtn
                v-permission="permission.del"
                :disabled="['1'].includes(row.inspectStatus)"
                :cbt="['是', '否']"
                icon="el-icon-delete"
                title="确定删除本条数据吗？"
                @confirm="onDelete(row)"
              >删除</WarningTextBtn>
              <el-button
                v-permission="permission.analyse"
                type="text"
                @click="viewStatistics(row)"
              >
                <svg-icon icon-class="international" style="margin-right: 5px;" />项目策划分析
              </el-button>
              <el-button
                v-permission="permission.scoreResult"
                type="text"
                icon="el-icon-edit"
                :disabled="['0'].includes(row.inspectStatus)"
                style="margin-left: 0"
                @click="onScoreResult(row)"
              >评分结果-评分表</el-button>
              <el-button style="margin-left: 0" icon="el-icon-message" type="text" @click="onRecords(row)">邮件发送记录</el-button>
              <el-button
                :disabled="['0'].includes(row.inspectStatus)"
                style="margin-left: 0"
                type="text"
                @click="viewTotalScore(row)"
              ><svg-icon icon-class="dictionary" /> 评分结果-数据分析</el-button>

            </div>
          </el-popover>
        </div>
      </template>
    </ProTable>
    <Details
      ref="detailsRef"
      title="审查策划"
      unique-id-name="planId"
      :form-column="formColumn"
      :form-rules="formRules"
      :add="add"
      :edit="edit"
      :default-form="defaultForm"
      @beforeClose="detailsClose"
    >
      <template #reviewYear="{ form, row }">
        <el-date-picker
          v-model="form.reviewYear"
          :default-value="new Date()"
          value-format="yyyy"
          type="year"
          placeholder="选择年"
          :disabled="row.disabled"
        />
      </template>
      <template #finishPlanTime="{ form, row }">
        <el-date-picker
          v-model="form.finishPlanTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"
          :disabled="row.disabled"
        />
      </template>
      <template #startInspectTime="{ form, row }">
        <el-date-picker
          v-model="form.startInspectTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"
          :disabled="row.disabled"
        />
      </template>
      <template #inspect1CompanyId_optionSlot="{ row }">
        <el-option
          v-for="item in optionFunc(row)"
          :key="item.id"
          :label="item.label"
          :value="item.id"
          :disabled="currentSelectProjct?.deptId === item.id ||
      detailsRef.submitForm.inspect2CompanyId === item.id
          "
        />
      </template>
      <template #inspect2CompanyId_optionSlot="{ row }">
        <el-option
          v-for="item in optionFunc(row)"
          :key="item.id"
          :label="item.label"
          :value="item.id"
          :disabled="currentSelectProjct?.deptId === item.id ||
      detailsRef.submitForm.inspect1CompanyId === item.id
          "
        />
      </template>
    </Details>
    <el-dialog title="邮件发送记录" :visible.sync="recordsVisible" :before-close="recordsVisibleHandleClose">
      <el-table stripe :data="recordsTableData" style="width: 100%">
        <el-table-column prop="sendTime" label="发送时间" />
        <el-table-column label="评审场次">
          <template slot-scope="{ row }">
            {{ getEnumlabel("inspect_plan_review_month", row.reviewMonth) }}
          </template>
        </el-table-column>
        <el-table-column label="邮件类型">
          <template slot-scope="{ row }">{{
            getEnumlabel("inspect_plan_email_type", row.type)
          }}</template>
        </el-table-column>
        <el-table-column prop="sendStatusDesc" label="发送状态" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
    </el-dialog>
    <RateResultDialog :visible.sync="dialogVisible" :total-score-message="totalScoreMessage" :is-getting="isGetting" :row-data="currentRow" />
    <!--  <el-dialog title="评分结果" :visible.sync="dialogVisible" width="800" :before-close="handleClose" custom-class="rate-dialog">
      <div v-loading="isGetting">
        <div class="control-part">
          <el-button @click="toggleExpand">{{ expandAll?"折叠":"展开" }}</el-button>
          <el-button v-for="btn in tabs" :key="btn.name" :type="btn.checked?'primary':''" @click="handleSingleBtnClick(btn)">{{ btn.title }}</el-button>
          <el-button style="float: right" :loading="downloadLoadingRate" @click="onDownloadRate(totalScoreMessage?.inspectPlanDto?.planId)">导出</el-button>
        </div>
        <el-collapse v-model="activeNames" @change="handleActiveNameChange">
          <el-collapse-item :title="formatTitle(tabs[0])" :name="tabs[0].name">
            <ProjectInfo :inspect-plan-dto="totalScoreMessage?.inspectPlanDto" />
          </el-collapse-item>
          <el-collapse-item :title="formatTitle(tabs[1])" :name="tabs[1].name">
            <div v-for="(val, key) in totalScoreMap" :key="key" class="total-score">
              <span>{{ val }}：</span>
              <span>{{ (totalScoreMessage['inspectPlanResultScoreMap'][key] === null || totalScoreMessage['inspectPlanResultScoreMap'][key] === undefined || totalScoreMessage['inspectPlanResultScoreMap'][key] === '') ? '' : totalScoreMessage['inspectPlanResultScoreMap'][key] }}</span>
            </div>
          </el-collapse-item>
          <el-collapse-item :title="formatTitle(tabs[2])" :name="tabs[2].name">
            <el-table stripe :data="totalScoreMessage.scoreDetailList" style="width: 100%" class="rate-dialog-table">
              <el-table-column label="专业" prop="discipline" header-align="center" />
              <el-table-column label="原策划数量（个）" header-align="center">
                <el-table-column label="必选项" prop="requiredNum" header-align="center" width="60" />
                <el-table-column label="可选项" prop="noRequiredNum" header-align="center" width="60" />
              </el-table-column>
              <el-table-column label="有效策划数量-不含标黄项（个）" header-align="center">
                <el-table-column label="必选项" prop="requiredTestNum" header-align="center" min-width="95" />
                <el-table-column label="可选项" prop="noRequiredTestNum" header-align="center" min-width="95" />
              </el-table-column>
              <el-table-column label="计入总分数量（个）" header-align="center">
                <el-table-column label="必选项" prop="requiredScoreNum" header-align="center" width="65" />
                <el-table-column label="可选项" prop="noRequiredScoreNum" header-align="center" width="65" />
              </el-table-column>
              <el-table-column label="分值（分）" header-align="center">
                <el-table-column label="必选项" prop="requiredScore" header-align="center" width="60" />
                <el-table-column label="可选项" prop="noRequiredScore" header-align="center" width="60" />
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <el-collapse-item :title="formatTitle(tabs[3])" :name="tabs[3].name">
            <div style="width: 100%;">
              <el-table stripe :data="totalScoreMessage.sumScoreDetailList" min-height="120" style="width: 100%" class="rate-dialog-table">
                <el-table-column label="专业" prop="standardDisciplineName" header-align="center" />
                <el-table-column label="数量（个）" header-align="center">
                  <el-table-column label="必选项" prop="getRequiredNum" header-align="center" />
                  <el-table-column label="可选项" prop="getNoRequiredNum" header-align="center" />
                </el-table-column>
                <el-table-column label="分值（分）" header-align="center">
                  <el-table-column label="必选项" prop="standardRequiredScore" header-align="center" />
                  <el-table-column label="可选项" prop="standardNoRequiredScore" header-align="center" />
                </el-table-column>
              </el-table>
            </div>

          </el-collapse-item>
        </el-collapse>
      </div>

    </el-dialog>-->
    <StatisticsDialog :visible.sync="statisticsDialogVisible" :statistics-data="statisticsData" :is-getting="isGettingStatistics" />
    <!-- <el-dialog title="项目策划分析" :visible.sync="statisticsDialogVisible" width="600" custom-class="rate-dialog-s">
      <div v-loading="isGettingStatistics">
        &lt;!&ndash;  <div class="base-title">基本信息</div>&ndash;&gt;
        <ProjectInfo :inspect-plan-dto="statisticsData?.inspectPlanDto" />
        <el-divider />
        <div style="width: 400px; margin: 40px auto; ">
          <Radar :chart-data="statisticsData?.chartData" width="360px" />
        </div>
      </div>

    </el-dialog>
    -->
    <el-dialog title="邮件发送失败" :visible.sync="errVisible" width="30%" :before-close="errVisibleHandleClose">
      <template v-for="(item, key) in errList">
        <div style="display: flex;justify-content: center;margin-bottom: 10px;">{{ key + 1 }}. {{ item }}</div>
      </template>
    </el-dialog>
    <LogDialog :log-type="REVIEW_PLANNING" :dialog-visible.sync="showLog" />
  </div>
</template>

<style  lang="scss">
.flex-box-review {
  gap: 10px;
  display: flex;
  align-items: center;
}

.operate-box-review{
  display: flex;
  align-items: center;
  justify-content: center;
}

.total-score {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;

  span {
    display: inline-block;
    width: 40%;
  }
}
::v-deep   .rate-dialog{
  width: 720px;
  .el-dialog__body{
      padding-top: 10px;
    }
  .control-part{
    margin-bottom: 10px;
  }
  .el-table__body-wrapper{
    min-height: 120px;
  }
  .rate-dialog-table.el-table tbody tr:hover > td{
    background-color: transparent !important
  }

  }

.base-title{
  line-height: 20px;
  background-color: #FFF;
  color: #303133;
  margin-bottom: 10px;
}
  .rate-dialog-s{
    width: 720px !important;
  }
</style>

<script>
export default { name: "ReviewPlanning" }
</script>
